package com.woaigsc.controller;

import com.woaigsc.pojo.Greeting;
import com.woaigsc.utils.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by chuiyuan on 3/19/16.
 */
@Controller
public class GreetController {
    private static final String template ="Hello, %s" ;
    private final AtomicLong counter = new AtomicLong();
    //DispatcherServlet
    //HandlerMapping
    //HandlerExecutionChain
    //HandlerInterceptor
    //HandlerAdapter
    //ViewResolver

    @RequestMapping("/greeting")
    @ResponseBody
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World")String name ) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }

    @RequestMapping("/greeting1")
    public void greeting1(@RequestParam(value = "name",defaultValue = "world")String name, HttpServletResponse resp){
        Greeting greeting = new Greeting(counter.incrementAndGet(),String.format(template,name ));
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try {
            PrintWriter writer = resp.getWriter() ;
            writer.print(JsonUtil.toJson(greeting));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/greeting2",method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String greeting2(@RequestParam(value = "name",defaultValue = "lisj")String name){
        Greeting greeting = new Greeting(counter.incrementAndGet(),String.format(template,name));
        return JsonUtil.toJson(greeting);
    }

}
